<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="用户id" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable @keyup.enter="handleQuery" />
      </el-form-item>-->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceId" style="width: 250px;">
        <!--        <el-input v-model="queryParams.serviceId" placeholder="请输入所属服务类型" clearable @keyup.enter="handleQuery" />-->
        <el-select v-model="queryParams.serviceId" placeholder="请选择所属服务类型" @change="handleQuery" clearable>
          <el-option v-for="item in serviceType" :key="item.serviceId" :label="item.serviceName"
            :value="item.serviceId" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务宣传" prop="serviceDesc">
        <el-input v-model="queryParams.serviceDesc" placeholder="请输入服务信息宣传" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="时间范围" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['provider:provider:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['provider:provider:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['provider:provider:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['provider:provider:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="providerList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户编号" align="center" prop="userId" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="服务编号" align="center" prop="serviceId" width="100" />
      <el-table-column label="服务类型" align="center" prop="serviceName" />
      <el-table-column label="服务宣传" align="center" prop="serviceDesc" show-overflow-tooltip />
      <el-table-column label="服务图片" align="center" prop="serviceImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.serviceImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span v-if="scope.row?.updateTime && scope.row.updateTime.trim() !== ''">
            {{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else>
            未更新
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['provider:provider:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['provider:provider:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改服务方登记信息 对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="providerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入绑定的用户id" @blur="exit" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceId">
          <el-select v-model="form.serviceId" placeholder="请选择所属服务类型">
            <el-option v-for="item in serviceType" :label="item.serviceName" :value="item.
              serviceId" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务宣传" prop="serviceDesc">
          <el-input type="textarea" :rows="3" v-model="form.serviceDesc" placeholder="请输入自定义服务信息宣传" />
        </el-form-item>
        <el-form-item label="服务图片" prop="serviceImg">
          <image-upload v-model="form.serviceImg" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="!form.userId || !form.serviceId || !form.phone">确
            定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Provider">
import { listProvider, getProvider, delProvider, addProvider, updateProvider } from "@/api/provider/provider"
import { listServicetype } from "@/api/servicetype/servicetype"
import { reactive } from "vue"
import { getUsers } from "../../../api/users/users"
import { parseTime } from "../../../utils/ruoyi.js";
const { proxy } = getCurrentInstance()
const dateRange = ref([])
const providerList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const serviceType = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    username: null,
    phone: null,
    serviceId: null,
    serviceDesc: null,
    serviceImg: null,
    beginTime: null,
    endTime: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

onMounted(() => {
  listServicetype().then(res => {
    serviceType.value = res.rows
    serviceType.value = serviceType.value.filter(item => item.status === '0');
    console.log(serviceType.value);
  })
  getList()
})

/** 查询服务方登记信息 列表 */
function getList() {
  loading.value = true
  listProvider({
    ...queryParams.value,
    // 明确传递日期范围参数
    beginTime: queryParams.value.beginTime,
    endTime: queryParams.value.endTime
  }).then(response => {
    providerList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

//判断是否有该用户
function exit() {
  getUsers(form.value.userId).then(res => {
    if (res.data === undefined) {
      proxy.$modal.msgError("用户不存在")
      form.value.userId = ""
    }
  })
}
// 表单重置
function reset() {
  form.value = {
    providerId: null,
    userId: null,
    phone: null,
    serviceId: null,
    serviceDesc: null,
    serviceImg: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("providerRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.providerId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加服务方登记信息 "
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _providerId = row.providerId || ids.value
  getProvider(_providerId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改服务方登记信息 "
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["providerRef"].validate(valid => {
    if (valid) {
      if (form.value.providerId != null) {
        updateProvider(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProvider(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _providerIds = row.providerId || ids.value
  proxy.$modal.confirm('是否确认删除服务方登记信息 编号为"' + _providerIds + '"的数据项？').then(function () {
    return delProvider(_providerIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('provider/provider/export', {
    ...queryParams.value
  }, `provider_${new Date().getTime()}.xlsx`)
}

</script>
